<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>邮件发送方配置管理</title>
    <!-- Reset Stylesheet -->
    <link rel="stylesheet" href="/back/css/reset.css" type="text/css" media="screen" />
    <!-- Main Stylesheet -->
    <link rel="stylesheet" href="/back/css/style.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="/back/css/invalid.css" type="text/css" media="screen" />

    <!-- jQuery -->
    <script type="text/javascript" src="/back/scripts/jquery-2.1.0.min.js"></script>
    <!-- jQuery Configuration -->
    <script type="text/javascript" src="/back/scripts/simpla.jquery.configuration.js"></script>

    <!-- dialog弹出框的导入-->
    <link rel="stylesheet" href="/back/widget/dialog/jquery-ui.min.css"/>
    <script type="text/javascript" src="/back/widget/dialog/jquery-ui-1.9.2.custom.min.js"></script>
    <script type="application/javascript" src="/commons/js/mydialog.js"></script>

    <!-- 引入ajax -->
    <script type="text/javascript" src="/commons/js/myajax.js"></script>

    <style>
        .config-card {
            border: 1px solid #ddd;
            margin: 10px 0;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 5px;
        }
        .config-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            padding-bottom: 10px;
            border-bottom: 1px solid #ddd;
        }
        .config-title {
            font-weight: bold;
            font-size: 16px;
        }
        .config-status {
            display: flex;
            gap: 5px;
        }
        .status-badge {
            padding: 2px 8px;
            border-radius: 3px;
            font-size: 12px;
            color: white;
        }
        .status-enabled { background: #4CAF50; }
        .status-disabled { background: #f44336; }
        .status-default { background: #ff9800; }
        .config-info p {
            margin: 5px 0;
            font-size: 14px;
        }
        .config-actions {
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid #ddd;
        }
        .config-actions .mybutton {
            margin-right: 5px;
        }
        .search-form {
            background: #f0f0f0;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
        }
        .search-form table {
            width: 100%;
        }
        .search-form td {
            padding: 5px;
            vertical-align: middle;
        }
        .form-row {
            margin-bottom: 15px;
        }
        .form-row label {
            display: inline-block;
            width: 120px;
            font-weight: bold;
        }
        .checkbox-group {
            display: flex;
            gap: 20px;
            margin-top: 5px;
        }
        .password-field {
            position: relative;
        }
        .password-toggle {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #666;
        }
    </style>

    <script>
        $(function () {
            loadConfigList();
        });

        // 加载配置列表
        function loadConfigList() {
            var configName = $('#searchConfigName').val();
            var senderEmail = $('#searchSenderEmail').val();
            var status = $('#searchStatus').val();
            
            var params = {};
            if (configName) params.configName = configName;
            if (senderEmail) params.senderEmail = senderEmail;
            if (status !== '') params.status = status === '1';
            
            $.get('/api/mail/sender/list', params, function(response) {
                if (response.code === 200) {
                    renderConfigList(response.data);
                } else {
                    alert('加载配置列表失败：' + response.message);
                }
            }).fail(function() {
                alert('网络错误，请重试');
            });
        }

        // 渲染配置列表
        function renderConfigList(configs) {
            var html = '';
            if (configs && configs.length > 0) {
                configs.forEach(function(config) {
                    html += '<div class="config-card">';
                    html += '<div class="config-header">';
                    html += '<div class="config-title">' + config.configName + '</div>';
                    html += '<div class="config-status">';
                    if (config.isDefault) {
                        html += '<span class="status-badge status-default">默认</span>';
                    }
                    html += '<span class="status-badge ' + (config.status ? 'status-enabled' : 'status-disabled') + '">';
                    html += config.status ? '启用' : '禁用';
                    html += '</span>';
                    html += '</div>';
                    html += '</div>';
                    html += '<div class="config-info">';
                    html += '<p><strong>SMTP服务器：</strong>' + config.smtpHost + ':' + config.smtpPort + '</p>';
                    html += '<p><strong>发送方邮箱：</strong>' + config.senderEmail + '</p>';
                    html += '<p><strong>发送方名称：</strong>' + (config.senderName || '未设置') + '</p>';
                    html += '<p><strong>加密方式：</strong>';
                    if (config.sslEnable) html += 'SSL ';
                    if (config.tlsEnable) html += 'TLS ';
                    if (!config.sslEnable && !config.tlsEnable) html += '无';
                    html += '</p>';
                    if (config.description) {
                        html += '<p><strong>描述：</strong>' + config.description + '</p>';
                    }
                    html += '</div>';
                    html += '<div class="config-actions">';
                    html += '<a href="javascript:void(0)" class="mybutton" onclick="editConfig(' + config.id + ')">编辑</a>';
                    html += '<a href="javascript:void(0)" class="mybutton" onclick="testConfig(' + config.id + ', \'' + config.configName + '\')">测试</a>';
                    if (!config.isDefault) {
                        html += '<a href="javascript:void(0)" class="mybutton" onclick="setDefault(' + config.id + ')">设为默认</a>';
                    }
                    html += '<a href="javascript:void(0)" class="mybutton" onclick="toggleStatus(' + config.id + ', ' + !config.status + ')">';
                    html += config.status ? '禁用' : '启用';
                    html += '</a>';
                    if (!config.isDefault) {
                        html += '<a href="javascript:void(0)" class="mybutton" onclick="deleteConfig(' + config.id + ')" style="background:#f44336">删除</a>';
                    }
                    html += '</div>';
                    html += '</div>';
                });
            } else {
                html = '<div style="text-align:center; padding:50px; color:#999;">暂无邮件发送方配置，请点击"新增配置"按钮添加</div>';
            }
            $('#configContainer').html(html);
        }

        // 搜索
        function searchConfig() {
            loadConfigList();
        }

        // 重置搜索
        function resetSearch() {
            $('#searchConfigName').val('');
            $('#searchSenderEmail').val('');
            $('#searchStatus').val('');
            loadConfigList();
        }

        // 新增配置
        function addConfig() {
            clearForm();
            $('#configId').val('');
            $('#dialogTitle').text('新增邮件发送方配置');
            $('#senderPassword').attr('placeholder', '请输入邮箱密码或授权码').prop('required', true);
            openDialog('dialog_add', '新增邮件发送方配置');
        }

        // 编辑配置
        function editConfig(id) {
            $.get('/api/mail/sender/detail/' + id, function(response) {
                if (response.code === 200) {
                    var config = response.data;
                    clearForm();
                    
                    $('#configId').val(config.id);
                    $('#configName').val(config.configName);
                    $('#smtpHost').val(config.smtpHost);
                    $('#smtpPort').val(config.smtpPort);
                    $('#senderEmail').val(config.senderEmail);
                    $('#senderName').val(config.senderName);
                    $('#connectionTimeout').val(config.connectionTimeout);
                    $('#readTimeout').val(config.readTimeout);
                    $('#description').val(config.description);
                    
                    $('#sslEnable').prop('checked', config.sslEnable);
                    $('#tlsEnable').prop('checked', config.tlsEnable);
                    $('#authEnable').prop('checked', config.authEnable);
                    $('#isDefault').prop('checked', config.isDefault);
                    $('#debugEnable').prop('checked', config.debugEnable);
                    
                    $('#dialogTitle').text('编辑邮件发送方配置');
                    $('#senderPassword').attr('placeholder', '不修改请留空').prop('required', false);
                    
                    openDialog('dialog_add', '编辑邮件发送方配置');
                } else {
                    alert('获取配置信息失败：' + response.message);
                }
            }).fail(function() {
                alert('网络错误，请重试');
            });
        }

        // 保存配置
        function saveConfig() {
            var configData = {
                id: $('#configId').val(),
                configName: $('#configName').val(),
                smtpHost: $('#smtpHost').val(),
                smtpPort: parseInt($('#smtpPort').val()),
                senderEmail: $('#senderEmail').val(),
                senderName: $('#senderName').val(),
                senderPassword: $('#senderPassword').val(),
                connectionTimeout: parseInt($('#connectionTimeout').val()),
                readTimeout: parseInt($('#readTimeout').val()),
                description: $('#description').val(),
                sslEnable: $('#sslEnable').is(':checked'),
                tlsEnable: $('#tlsEnable').is(':checked'),
                authEnable: $('#authEnable').is(':checked'),
                isDefault: $('#isDefault').is(':checked'),
                debugEnable: $('#debugEnable').is(':checked')
            };
            
            var isEdit = !!configData.id;
            var url = isEdit ? '/api/mail/sender/update' : '/api/mail/sender/create';
            
            // 如果是编辑且密码为空，则不传递密码字段
            if (isEdit && !configData.senderPassword) {
                delete configData.senderPassword;
            }
            
            $.ajax({
                url: url,
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(configData),
                success: function(response) {
                    if (response.code === 200) {
                        alert(isEdit ? '更新配置成功！' : '创建配置成功！');
                        closeDialog();
                        loadConfigList();
                    } else {
                        alert((isEdit ? '更新' : '创建') + '配置失败：' + response.message);
                    }
                },
                error: function() {
                    alert('网络错误，请重试');
                }
            });
        }

        // 测试配置
        function testConfig(id, name) {
            var testEmail = prompt('请输入测试邮箱地址：');
            if (testEmail) {
                $.post('/api/mail/sender/test', {
                    configId: id,
                    testEmail: testEmail
                }, function(response) {
                    if (response.code === 200) {
                        alert('测试邮件发送成功！请检查邮箱');
                    } else {
                        alert('测试邮件发送失败：' + response.message);
                    }
                }, 'json').fail(function() {
                    alert('网络错误，请重试');
                });
            }
        }

        // 设置默认配置
        function setDefault(id) {
            if (confirm('确定要设置为默认配置吗？')) {
                $.post('/api/mail/sender/setDefault/' + id, function(response) {
                    if (response.code === 200) {
                        alert('设置默认配置成功');
                        loadConfigList();
                    } else {
                        alert('设置默认配置失败：' + response.message);
                    }
                }, 'json');
            }
        }

        // 切换状态
        function toggleStatus(id, status) {
            var action = status ? '启用' : '禁用';
            if (confirm('确定要' + action + '该配置吗？')) {
                $.post('/api/mail/sender/updateStatus', {
                    id: id,
                    status: status
                }, function(response) {
                    if (response.code === 200) {
                        alert(action + '配置成功');
                        loadConfigList();
                    } else {
                        alert(action + '配置失败：' + response.message);
                    }
                }, 'json');
            }
        }

        // 删除配置
        function deleteConfig(id) {
            if (confirm('确定要删除该配置吗？删除后不可恢复！')) {
                $.post('/api/mail/sender/delete/' + id, function(response) {
                    if (response.code === 200) {
                        alert('删除配置成功');
                        loadConfigList();
                    } else {
                        alert('删除配置失败：' + response.message);
                    }
                }, 'json');
            }
        }

        // 清空表单
        function clearForm() {
            $('#myform')[0].reset();
            $('#configId').val('');
        }

        // 切换密码显示
        function togglePassword() {
            var passwordField = $('#senderPassword');
            var toggleIcon = $('.password-toggle');
            
            if (passwordField.attr('type') === 'password') {
                passwordField.attr('type', 'text');
                toggleIcon.text('隐藏');
            } else {
                passwordField.attr('type', 'password');
                toggleIcon.text('显示');
            }
        }
    </script>
</head>
<body>
<div id="main-content">
    <div class="content-box">
        <div class="content-box-content">
            <h2>邮件发送方配置管理</h2>
            <br/>
            
            <!-- 搜索表单 -->
            <div class="search-form">
                <table>
                    <tr>
                        <td>配置名称：</td>
                        <td><input type="text" id="searchConfigName" class="text-input" placeholder="请输入配置名称"></td>
                        <td>发送方邮箱：</td>
                        <td><input type="text" id="searchSenderEmail" class="text-input" placeholder="请输入发送方邮箱"></td>
                        <td>状态：</td>
                        <td>
                            <select id="searchStatus" class="text-input">
                                <option value="">全部</option>
                                <option value="1">启用</option>
                                <option value="0">禁用</option>
                            </select>
                        </td>
                        <td>
                            <button type="button" class="mybutton" onclick="searchConfig()">搜索</button>
                            <button type="button" class="mybutton" onclick="resetSearch()">重置</button>
                        </td>
                    </tr>
                </table>
            </div>
            
            <!-- 操作按钮 -->
            <div style="margin-bottom: 20px;">
                <a class="mybutton" href="javascript:addConfig();">新增配置</a>
                <a class="mybutton" href="javascript:loadConfigList();">刷新列表</a>
            </div>
            
            <!-- 配置列表 -->
            <div id="configContainer"></div>
        </div>
    </div>
</div>

<!-- 新增/编辑配置对话框 -->
<div id="dialog_add" style="display: none;">
    <div class="content-box-content">
        <h2 id="dialogTitle">新增邮件发送方配置</h2>
        
        <form id="myform">
            <input type="hidden" id="configId">
            
            <div class="form-row">
                <label>配置名称：<span style="color:red">*</span></label>
                <input class="text-input large-input" type="text" id="configName" placeholder="请输入配置名称" required>
            </div>
            
            <div class="form-row">
                <label>发送方显示名称：</label>
                <input class="text-input large-input" type="text" id="senderName" placeholder="请输入发送方显示名称">
            </div>
            
            <div class="form-row">
                <label>SMTP服务器：<span style="color:red">*</span></label>
                <input class="text-input large-input" type="text" id="smtpHost" placeholder="例如：smtp.qq.com" required>
            </div>
            
            <div class="form-row">
                <label>SMTP端口：<span style="color:red">*</span></label>
                <input class="text-input" type="number" id="smtpPort" placeholder="例如：587" value="587" required>
            </div>
            
            <div class="form-row">
                <label>发送方邮箱：<span style="color:red">*</span></label>
                <input class="text-input large-input" type="email" id="senderEmail" placeholder="请输入发送方邮箱" required>
            </div>
            
            <div class="form-row">
                <label>邮箱密码：<span style="color:red">*</span></label>
                <div class="password-field">
                    <input class="text-input large-input" type="password" id="senderPassword" placeholder="请输入邮箱密码或授权码" required>
                    <span class="password-toggle" onclick="togglePassword()">显示</span>
                </div>
            </div>
            
            <div class="form-row">
                <label>连接超时(ms)：</label>
                <input class="text-input" type="number" id="connectionTimeout" value="10000">
            </div>
            
            <div class="form-row">
                <label>读取超时(ms)：</label>
                <input class="text-input" type="number" id="readTimeout" value="10000">
            </div>
            
            <div class="form-row">
                <label>配置选项：</label>
                <div class="checkbox-group">
                    <label><input type="checkbox" id="sslEnable"> 启用SSL</label>
                    <label><input type="checkbox" id="tlsEnable" checked> 启用TLS</label>
                    <label><input type="checkbox" id="authEnable" checked> 需要认证</label>
                    <label><input type="checkbox" id="isDefault"> 设为默认</label>
                    <label><input type="checkbox" id="debugEnable"> 启用调试</label>
                </div>
            </div>
            
            <div class="form-row">
                <label>配置描述：</label>
                <textarea class="text-input large-input" id="description" rows="3" placeholder="可选，配置的描述信息"></textarea>
            </div>
            
            <div class="form-row">
                <button type="button" class="mybutton" onclick="saveConfig();">保存</button>
                <button type="reset" class="mybutton">重置</button>
                <button type="button" class="mybutton" onclick="closeDialog();">取消</button>
            </div>
        </form>
    </div>
</div>
</body>
</html>